package org.lionsoul.websnail.downloader;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.lionsoul.websnail.util.DefaultLinkExtractor;
import org.lionsoul.websnail.util.LinkExtractor;

/**
 * Page manager class. <br />
 * <p>
 * When the Worker finished the PageTask, it will create
 * a Page instance itself to hold the downloaded data to analysis. <br />
 * <p>
 * So, you can invoke you PageAnalyzer to analysis the data. <br />
 * <p>
 * also, it offer interface to store some analysised fields. <br />
 *
 * @author chenxin,yangjian
 */
public class Page {
    /**
     * the url of the current page
     */
    private String url = null;

    /**
     * Owing to the design, the url may not be
     * the direct url that could be access by http client
     */
    private String originUrl = null;

    /**
     * the html content of the current page
     */
    private String html = null;

    /**
     * link extractor
     */
    private final LinkExtractor linkExtractor;

    /**
     * create a new Page
     */
    public static Page create() {
        return new Page(null);
    }

    public Page(String url) {
        this.linkExtractor = DefaultLinkExtractor.create();
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public Page setUrl(String url) {
        this.url = url;
        return this;
    }

    public String getOriginUrl() {
        return originUrl;
    }

    public Page setOriginUrl(String originUrl) {
        this.originUrl = originUrl;
        return this;
    }

    public String getHtml() {
        return html;
    }

    public Page setHtml(String html) {
        this.html = html;
        return this;
    }

    public LinkExtractor getLinkExtractor() {
        return linkExtractor;
    }

    /**
     * get all the links created by the current LinkExtractor
     * you could change the default linkExtractor by invoke {@code setLinkExtractor}
     * or the {@link org.lionsoul.websnail.util.DefaultLinkExtractor} will be used
     * <p>
     * or set the setting of the extractor by getLinkExtractor and invoke its
     * serials of set methods
     *
     * @return String[]
     */
    public String[] getLinks() {
        //get the extracted links
        return linkExtractor
                .setHtml(html)
                .setUrl(url)
                .extract();
    }

    // 解析 JSON 字符串内容
    public JSONObject getJsonObject() {
        return JSON.parseObject(html);
    }

    // 解析 JSON 字符串并返回指定类型的 Java 对象
    public <T> T getJsonObject(Class<T> clazz) {
        return JSONObject.toJavaObject(JSON.parseObject(html), clazz);
    }
}
